package com.cino.demos.shortlink.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class UrlShortener {
    private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int CODE_LENGTH = 6;
    private static final Map<String, String> urlMapping = new HashMap<>();
    private static final Random random = new Random();

    // 方法：生成随机的6位短码
    private static String generateRandomCode() {
        StringBuilder code;
        do {
            code = new StringBuilder(CODE_LENGTH);
            for (int i = 0; i < CODE_LENGTH; i++) {
                int index = random.nextInt(CHARACTERS.length());
                code.append(CHARACTERS.charAt(index));
            }
        } while (urlMapping.containsValue(code.toString())); // 确保短码唯一
        return code.toString();
    }

    // 方法：将原网址转换为短码
    public static String shortenUrl(String originalUrl) {
        // 首先检查是否已存在对应的短码
        if (urlMapping.containsKey(originalUrl)) {
            return urlMapping.get(originalUrl); // 如果网址已存在，直接返回已生成的短码
        }

        // 生成基于原网址的哈希前缀
        String hash = getHash(originalUrl);
        String shortCode = hash.substring(0, 3) + generateRandomCode(); // 前三位来自哈希后续随机生成
        urlMapping.put(originalUrl, shortCode);
        return shortCode;
    }

    // 方法：计算原网址的哈希值
    private static String getHash(String originalUrl) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(originalUrl.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString(); // 返回原网址的MD5哈希
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 方法：根据短码获取原网址
    public static String getOriginalUrl(String shortCode) {
        for (Map.Entry<String, String> entry : urlMapping.entrySet()) {
            if (entry.getValue().equals(shortCode)) {
                return entry.getKey();
            }
        }
        return null; // 如果找不到对应的原网址
    }

    public static void main(String[] args) {
        // 测试示例
        String originalUrl1 = "https://www.bilibili.com/video/BV1vf421i7hV?spm_id_from=333.788.videopod.episodes&vd_source=5951f25d79b162d0d6918adcc1984db1&p=31";
        String originalUrl2 = "https://gitee.com/cino333";

        String shortCode1 = shortenUrl(originalUrl1);
        String shortCode2 = shortenUrl(originalUrl2);

        System.out.println("Original URL 1: " + originalUrl1);
        System.out.println("Shortened Code 1: " + shortCode1);

        System.out.println("Original URL 2: " + originalUrl2);
        System.out.println("Shortened Code 2: " + shortCode2);

        // 测试反向查找
//        String retrievedUrl1 = getOriginalUrl(shortCode1);
//        System.out.println("Retrieved URL 1: " + retrievedUrl1);
//
//        String retrievedUrl2 = getOriginalUrl(shortCode2);
//        System.out.println("Retrieved URL 2: " + retrievedUrl2);
    }
}
